<template>
  <a-card :bordered="false" :bodyStyle="{padding:'24px 0px 24px 0px'}">
    <a-tabs default-active-key="unhandled" tabPosition="left" @change="tabChange">
      <a-tab-pane key="unhandled">
        <span slot="tab"><a-icon type="user" /> 未办理</span>
      </a-tab-pane>
      <a-tab-pane key="handled">
        <span slot="tab"><a-icon type="clock-circle" />已办理</span>
      </a-tab-pane>
      <a-spin size="large" :delay="1000" :spinning="spinning" >
      <!-- 查询区域 -->
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="24">
            <a-col :xl="6" :lg="7" :md="8" :sm="24" >
              <a-form-item label="流程编码">
                <a-input v-model="queryParam.modelKey" placeholder="请输入流程编码"/>
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="7" :md="8" :sm="24" >
              <a-form-item label="流程名称">
                <a-input v-model="queryParam.modelName" placeholder="请输入流程名称"/>
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
                <a-button  type="primary" icon="search" @click="searchQuery">查询</a-button>
                <a-button type="primary" icon="reload" style="margin-left: 8px" @click="searchReset">重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <!-- table区域-begin -->
      <div>
        <a-table
          size="middle"
          bordered
          row-key="id"
          :columns="columns"
          :data-source="dataSource"
          :pagination="ipagination"
          :loading="loading"
          @change="handleTableChange"
        >
          <template slot="action" slot-scope="text, record">
            <a v-if="record.status === 0 || record.status === 3 || record.status === 5" @click="startInstance(record)">提交流程</a>
            <a-divider v-if="record.status === 0 || record.status === 3 || record.status === 5" type="vertical" />
            <a-dropdown>
              <a class="ant-dropdown-link">更多<a-icon type="down" /></a>
              <a-menu slot="overlay">
                <a-menu-item v-if="record.status === 0 || record.status === 3|| record.status === 5">
                  <a @click="handleEdit_(record)">编辑</a>
                </a-menu-item>
                <a-menu-item v-if="record.status === 1">
                  <a @click="urgingClick(record)">催办</a>
                </a-menu-item>
                <a-menu-item>
                  <a @click="handleDetails_(record)">详情</a>
                </a-menu-item>
                <a-menu-item v-if="record.status !== 0">
                  <a @click="handleHistory(record)">审批进度</a>
                </a-menu-item>
                <a-menu-item v-if="record.status === 2 && record.reportCode" >
                  <a @click="handlePrint(record)">打印</a>
                </a-menu-item>
                <a-menu-item v-if="record.status === 0 || record.status === 3 || record.status === 5">
                  <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.formDataId)">
                    <a>删除</a>
                  </a-popconfirm>
                </a-menu-item>
              </a-menu>
            </a-dropdown>
          </template>
        </a-table>
      </div>
      <j-modal
        width="80%"
        :title="kfbTitle"
        :visible.sync="desformApplyVisible"
        :fullscreen.sync="fullscreen"
        :switch-fullscreen="switchFullscreen"
        @cancel="desformApplyHandleCancel"
        :destroyOnClose="true"
      >
        <template slot="footer" v-if="isShowFooter">
          <a-button @click="desformApplyHandleCancel">取消</a-button>
          <a-button
            type="primary"
            @click="desformApplyHandleOk"
          >
            确定
          </a-button>
        </template>
        <k-form-build ref="kfb" :value="kfdJsonData" :disabled="disabledAll" />
      </j-modal>
      <!-- 审批进度 -->
      <task-modal ref="taskModal" title="审批进度" :taskData="taskData" type="history"></task-modal>
      </a-spin>
    </a-tabs>
  </a-card>
</template>

<script>
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { getAction } from '@/api/manage'
import { filterDictTextByCache } from '@/components/dict/JDictSelectUtil'
import { saveOrUpdate, startInstance } from '@/api/process'
import taskModal from '@/views/modules/task/modal/TaskModal'
import { urging } from '@/api/task'
import { mapGetters } from 'vuex'
import { KFormBuild } from '@/components/k-form-design/index'
import { filterObj,getLikeOrEqQueryParam } from '@/utils/util'
export default {
  name: 'ExtActDesignFlowDataList',
  components: {
    taskModal,
    KFormBuild
  },
  mixins: [JeecgListMixin],
  data() {
    return {
      fullscreen: false,
      switchFullscreen: true,
      columns: [// 表头
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '流程名称',
          align: 'center',
          dataIndex: 'modelName'
        },
        {
          title: '流程编码',
          align: 'center',
          dataIndex: 'modelKey'
        },
        {
          title: '业务板块',
          align: 'center',
          dataIndex: 'businessPlate',
          customRender: (text) => {
            return filterDictTextByCache('business_sector', text)
          }
        },
        {
          title: '创建时间',
          align: 'center',
          dataIndex: 'createTime'
        },
        {
          title: '状态',
          align: 'center',
          dataIndex: 'status',
          customRender: (text) => {
            return filterDictTextByCache('bpmn_status', text)
          }
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          scopedSlots: { customRender: 'action' }
        }
      ],
      url: {
        list: '/activiti/formData/list',
        delete: '/activiti/formData/delete',
        getKfdJson: '/activiti/form/getFormByProcessDefinitionId' // 自定义表单查询
      },
      kfbTitle: '',
      desformApplyVisible: false,
      disabledAll: false,
      kfdJsonData: {},
      modelId: '',
      formId: '',
      formDataId: '',
      taskData: {},
      spinning: false,
      isShowFooter: true, // 控制是否显示弹窗底部按钮
      expandParam: {}
    }
  },
  methods: {
    ...mapGetters(['userInfo', 'token']),
    loadData(arg) { // 需要添加一个根据用户查询的条件
      if (!this.url.list) {
        this.$message.error('请设置url.list属性!')
        return
      }
      // 加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1
      }
      var params = this.getQueryParams()// 查询条件
      this.loading = true
      params.createBy = this.userInfo().username// 添加用户查询的条件
      params.type = 2
      getAction(this.url.list, params).then((res) => {
        if (res.success) {
          this.dataSource = res.result.records
          this.ipagination.total = res.result.total
        }
        if (res.code === 510) {
          this.$message.warning(res.message)
        }
        this.loading = false
      })
    },
    handleEdit_(item) {
      this.isShowFooter = true
      this.disabledAll = false
      this.kfbTitle = '编辑【' + item.modelName + '】'
      this.getKfdJson(item)
    },
    handleDetails_(item) {
      this.isShowFooter = null
      this.disabledAll = true
      this.kfbTitle = '详情【' + item.modelName + '】'
      this.getKfdJson(item)
    },
    desformApplyHandleCancel() {
      this.desformApplyVisible = false
    },
    async desformApplyHandleOk() {
      try {
        const formData = await this.$refs.kfb.getData()
        const res = await saveOrUpdate({
          modelId: this.modelId,
          formId: this.formId,
          formData: JSON.stringify(formData),
          id: this.formDataId,
          type: 2// 区分是否在我的工单页面显示
        })
        if (res.success) {
          this.desformApplyVisible = false
          this.$message.success('保存成功')
          this.loadData()
        } else {
          this.$message.warning(res.message)
        }
      } catch (err) {
        console.log(err)
      }
    },
    async getKfdJson(item) {
      try {
        const res = await getAction(this.url.getKfdJson, { modelId: item.modelId, processDefinitionId: item.processDefinitionId })
        if (res.success) {
          if (!res.result) {
            return this.$message.warning('该工单的未设计表单')
          }
          this.modelId = item.modelId
          this.formId = item.formId
          this.formDataId = item.formDataId
          this.kfdJsonData = JSON.parse(res.result.htmlJson)
          this.desformApplyVisible = true
          this.$nextTick(() => {
            this.$refs.kfb.setData(JSON.parse(item.formData))
          })
        } else {
          this.$message.warning(res.message)
        }
      } catch (err) {
        console.log(err)
      }
    },
    startInstance(item) {
      const that = this
      this.$confirm({
        title: '确认提交流程',
        content: '是否提交该流程?',
        cancelText: '取消',
        okText: '确定',
        onOk() {
          that.spinning = true
          startInstance({
            modelId: item.modelId,
            formDataId: item.formDataId,
            processDefinitionId: item.processDefinitionId
          }).then(res => {
            that.spinning = false
            if (res.success) {
              that.$message.success(res.message)
              that.loadData()
            } else {
              that.$message.warning(res.message)
            }
          })
        }
      })
    },
    handleHistory(data) { // 点击查看进度
      this.taskData = data
      this.$refs.taskModal.editModalVisible = true
    },
    handlePrint(data) {
      console.log(data)
      const token = this.token()
      let url = `${window._CONFIG['domianURL']}/jmreport/view/${data.reportCode}?token=${token}`
      url += `&id=${data.formDataId}&processInstanceId=${data.processInstanceId}`
      window.open(url)
    },
    urgingClick(item) { // 点击催办
      // this.$refs.urgingModal.modalVisible = true
      urging({ procInstId: item.processInstanceId }).then(res => {
        if (res.success) {
          this.$message.success('催办成功')
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    tabChange(activeKey) {
      if (activeKey === 'unhandled') {
        this.expandParam.status = '2,4'
      } else {
        this.expandParam.status = '0,1,3,5,6,7'
      }
    },
    getQueryParams() {
      // 获取查询条件
      const sqp = {}
      if (this.superQueryParams) {
        sqp['superQueryParams'] = encodeURI(this.superQueryParams)
        sqp['superQueryMatchType'] = this.superQueryMatchType
      }
      const queryParam = getLikeOrEqQueryParam(this.queryParam)
      var param = Object.assign(sqp, queryParam, this.isorter, this.filters, this.expandParam)
      param.field = this.getQueryField()
      param.pageNo = this.ipagination.current
      param.pageSize = this.ipagination.pageSize
      return filterObj(param)
    }
  }
}
</script>
<style scoped>
  @import '~@assets/less/common.less';

</style>
